package com.tz.crm.dao.impl;

import com.tz.crm.dao.AreaDao;
import com.tz.crm.entity.Area;
import org.hibernate.query.Query;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import java.util.List;

/**
 * AreaDaoImpl
 */
@Repository
@Transactional
public class AreaDaoImpl extends BaseDaoImpl<Area, String> implements AreaDao {

    @Override
    public Area getById(String id) {
        //init CriteriaBuilder
        CriteriaBuilder cb = getSession().getCriteriaBuilder();
        //init CriteriaQuery
        CriteriaQuery<Area> cq = cb.createQuery(Area.class);
        //init Root
        Root<Area> root = cq.from(Area.class);
        //select a from Area a where id =:id
        cq.select(root).where(cb.equal(root.get("id"),id));
        Query query = getSession().createQuery(cq);
        return (Area) query.uniqueResult();
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<Area> getAreaWithChildren(String name) {
        String hql = "from Area a where a.parent.name=:name order by a.name";
        List<Area> list = getSession().createQuery(hql)
                .setParameter("name", name)
                .list();
        return list;
    }

    @Override
    public Area getByName(String name) {
        String hql = "from Area a join fetch a.children where a.name = :name";
        return (Area) getSession().createQuery(hql)
                .setParameter("name", name)
                .uniqueResult();
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<Area> getByLevel(int level) {
        //查询结果根据英文26个字母升序排序
        String hql = "from Area a where a.level = :level order by a.name asc";
        return getSession().createQuery(hql)
                .setParameter("level", level)
                .list();
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<Area> getChildrenByParentId(String id) {
        //查询结果根据英文26个字母升序排序
        String hql = "from Area a where a.parent.id=:id order by a.name";
        List<Area> list = getSession().createQuery(hql)
                .setParameter("id", id)
                .list();
        return list;
    }
}
